package orm

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	glog "gorm.io/gorm/logger"
	"time"
	"zsc-boot/core"
)

type OrmLogByZap struct {
	LogLevel glog.LogLevel
	l        *zap.Logger
}

func NewOrmLogByZap() *OrmLogByZap {
	tmp := zap.New(zapcore.NewTee(core.BuildConsoleZapCore(),
		core.BuildFileZapCore("info", "json", core.GetFileWriter())), zap.AddCaller(), zap.AddCallerSkip(3))
	return &OrmLogByZap{
		l: tmp,
	}
}

func (o *OrmLogByZap) LogMode(level glog.LogLevel) glog.Interface {
	newlogger := *o
	newlogger.LogLevel = level
	return &newlogger
}

func (o *OrmLogByZap) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
	elapsed := time.Since(begin)
	sql, row := fc()
	str := ""
	if err != nil {
		str = fmt.Sprintf("%s SQL:\n %s \n [%s,%d]", err.Error(), sql, elapsed, row)
	} else {
		str = fmt.Sprintf("\n %s \n [%s,%d]", sql, elapsed, row)
	}
	o.l.Info(str)
}

// Info print info
func (o *OrmLogByZap) Info(ctx context.Context, msg string, data ...interface{}) {
	o.l.Info(msg)
}

// Warn print warn messages
func (o *OrmLogByZap) Warn(ctx context.Context, msg string, data ...interface{}) {
	o.l.Warn(msg)
}

// Error print error messages
func (o *OrmLogByZap) Error(ctx context.Context, msg string, data ...interface{}) {
	o.l.Error(msg)
}
